/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.web.editors.workbench;

import cn.easyplatform.entities.BaseEntity;
import cn.easyplatform.entities.EntityInfo;
import cn.easyplatform.entities.beans.LogicBean;
import cn.easyplatform.entities.beans.report.JasperReportBean;
import cn.easyplatform.entities.transform.TransformerFactory;
import cn.easyplatform.lang.Lang;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.entity.GetEntryCmd;
import cn.easyplatform.studio.cmd.entity.LockCmd;
import cn.easyplatform.studio.cmd.entity.SaveCmd;
import cn.easyplatform.studio.cmd.version.GetCmd;
import cn.easyplatform.studio.cmd.version.HistoryCmd;
import cn.easyplatform.studio.context.Contexts;
import cn.easyplatform.studio.utils.StudioUtil;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.EntityVo;
import cn.easyplatform.studio.vos.HistoryVo;
import cn.easyplatform.studio.web.editors.AbstractPanelEditor;
import cn.easyplatform.studio.web.editors.Editor;
import cn.easyplatform.studio.web.layout.WorkbenchController;
import cn.easyplatform.type.EntityType;
import cn.easyplatform.web.ext.cmez.CMeditor;
import org.ocpsoft.prettytime.PrettyTime;
import org.zkoss.lang.Objects;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.*;

import java.util.List;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class HistoryEditor extends AbstractPanelEditor {

    private CMeditor editor;

    private Listbox history;

    private EntityVo entity;

    private String content;

    private Checkbox highlight;

    private Checkbox connect;

    private Checkbox collapse;

    private Checkbox threeway;

    private Button replace;

    private String histValue;

    private String reportContent;

    /**
     * @param workbench
     * @param id
     */
    public HistoryEditor(WorkbenchController workbench, String id) {
        super(workbench, id);
    }

    @Override
    public void create(Object... args) {
        EntityVo entity = (EntityVo) args[0];
        if (this.entity != null && !this.entity.getId().equals(entity.getId())) {
            this.entity = entity;
            content = StudioApp.execute(new GetEntryCmd(entity.getId()))
                    .getContent();
            if (entity.getType().equals(EntityType.REPORT.getName()))
                content = StudioUtil.convertReportContent(content);
            else if (entity.getType().equals(EntityType.LOGIC.getName()))
                editor.setMode("epscript");
            editor.setOrig(null);
            editor.setValue(content);
            histValue = null;
            replace.setDisabled(true);
            threeway.setChecked(false);
            ((South) history.getParent().getParent()).setTitle(entity.getId() + "-"
                    + entity.getName() + ":");
        } else if (this.entity == null) {
            this.entity = entity;
            content = StudioApp.execute(new GetEntryCmd(entity.getId()))
                    .getContent();
            if (entity.getType().equals(EntityType.REPORT.getName()))
                content = StudioUtil.convertReportContent(content);
            Idspace is = createPanel(Labels.getLabel("navi.history.tab.info"), "~./images/svn/showhistory.gif", "~./include/editor/workbench/history.zul");
            for (Component comp : is.getFellows()) {
                if (comp.getId().equals("history")) {
                    history = (Listbox) comp;
                    history.setPageSize(5);
                    history.getPaginal().setPageSize(5);
                    history.addEventListener(Events.ON_SELECT, this);
                } else if (comp.getId().equals("editor")) {
                    editor = (CMeditor) comp;
                    editor.setTheme(Contexts.getUser().getEditorTheme());
                } else if (comp instanceof Checkbox) {
                    if (comp.getId().equals("highlight"))
                        highlight = (Checkbox) comp;
                    else if (comp.getId().equals("connect"))
                        connect = (Checkbox) comp;
                    else if (comp.getId().equals("collapse"))
                        collapse = (Checkbox) comp;
                    else if (comp.getId().equals("threeway"))
                        threeway = (Checkbox) comp;
                    comp.addEventListener(Events.ON_CHECK, this);
                } else if (comp.getId().equals("replace")) {
                    replace = (Button) comp;
                    replace.addEventListener(Events.ON_CLICK, this);
                }
            }
            if (entity.getType().equals(EntityType.LOGIC.getName()))
                editor.setMode("epscript");
            editor.setValue(content);
            replace.setDisabled(true);
        }
        redraw();
    }

    private void redraw() {
        history.getItems().clear();
        List<HistoryVo> histories = StudioApp.execute(new HistoryCmd(entity
                .getId()));
        PrettyTime pretty = new PrettyTime();
        for (HistoryVo vo : histories) {
            Listitem li = new Listitem();
            li.appendChild(new Listcell(vo.getVersion() + ""));
            li.appendChild(new Listcell(vo.getName()));
            li.appendChild(new Listcell(vo.getDesp()));
            li.appendChild(new Listcell(vo.getCommitter()));
            li.appendChild(new Listcell(pretty.format(vo.getCommittedDate())));
            li.appendChild(new Listcell(vo.getStatus()));
            li.setValue(vo);
            li.setParent(history);
        }
    }

    @Override
    public void dispatch(Event event) {
        if (event.getName().equals(Events.ON_SELECT)) {// 列表选择
            if (histValue == null) {
                highlight.setChecked(true);
                connect.setChecked(false);
                collapse.setChecked(false);
                if (StudioUtil.isEditPermission(entity))
                    replace.setDisabled(false);
            }
            HistoryVo vo = history.getSelectedItem().getValue();
            String value = StudioApp.execute(new GetCmd(vo.getVersion()));
            if (entity.getType().equals(EntityType.REPORT.getName())) {
                reportContent = value;
                value = StudioUtil.convertReportContent(value);
            }
            if (threeway.isChecked())
                editor.setOrigLeft(value);
            else if (!Objects.equals(value, histValue)) {
                editor.setOrig(value);
                histValue = value;
                if (StudioUtil.isEditPermission(entity))
                    replace.setDisabled(content.equals(value));
            }
        } else if (event.getName().equals(Events.ON_CHECK)) {// Switchbox
            if (event.getTarget() == highlight)
                editor.setHighlightSelection(highlight.isChecked());
            else if (event.getTarget() == connect)
                editor.setConnect(connect.isChecked() ? "align" : null);
            else if (event.getTarget() == collapse)
                editor.setCollapse(collapse.isChecked());
            else if (event.getTarget() == threeway) {
                if (!threeway.isChecked())
                    editor.setOrigLeft(null);
            }
        } else if (event.getTarget() == replace) {// Button
            WebUtils.showConfirm(Labels.getLabel("menu.replace"), this);
        } else if (event.getName().equals(Events.ON_OK)) {// Messagebox.OK
            HistoryVo vo = history.getSelectedItem().getValue();
            EntityInfo ei = new EntityInfo();
            ei.setId(entity.getId());
            ei.setName(vo.getName());
            if (entity.getType().equals(EntityType.REPORT.getName()))
                ei.setContent(reportContent);
            else
                ei.setContent(histValue);
            ei.setDescription(vo.getDesp());
            ei.setType(entity.getType());
            ei.setSubType(entity.getSubType());
            ei.setStatus('U');
            StudioApp.execute(new SaveCmd(ei));
            editor.setValue(histValue);
        } else if (event.getTarget() instanceof A) {// Listbox
            Listitem li = (Listitem) event.getTarget().getParent().getParent();
            HistoryVo vo = li.getValue();
            String c = StudioApp.execute(new GetCmd(vo.getVersion()));
            Editor editor = workbench.checkEditor(entity.getId());
            // 先尝试记录锁
            String lockUser = StudioApp.execute(new LockCmd(entity.getId()));
            char code = 'U';
            if (!Strings.isBlank(lockUser)) {
                code = 'R';
                Messagebox.show(Labels.getLabel("enitiy.locked",
                        new String[]{lockUser}), Labels
                                .getLabel("message.title.error"), Messagebox.OK,
                        Messagebox.INFORMATION);
            }
            BaseEntity e = null;
            if (entity.getType().equals(EntityType.LOGIC.getName())) {
                LogicBean logic = new LogicBean();
                logic.setId(entity.getId());
                logic.setName(vo.getName());
                logic.setDescription(vo.getDesp());
                logic.setType(entity.getType());
                logic.setSubType(entity.getSubType());
                logic.setContent(c);
                e = logic;
            } else if (entity.getType().equals(EntityType.REPORT.getName())) {
                JasperReportBean report = TransformerFactory.newInstance()
                        .transformFromXml(JasperReportBean.class, Lang.ins(c));
                report.setId(entity.getId());
                report.setName(vo.getName());
                report.setDescription(vo.getDesp());
                report.setType(entity.getType());
                report.setSubType(entity.getSubType());
                e = report;
            } else {
                EntityInfo ie = new EntityInfo();
                ie.setId(entity.getId());
                ie.setName(vo.getName());
                ie.setDescription(vo.getDesp());
                ie.setType(entity.getType());
                ie.setSubType(entity.getSubType());
                ie.setContent(c);
                e = TransformerFactory.newInstance().transformFromXml(ie);
            }
            if (editor == null)
                workbench.createEditor(e, code);
            else
                editor.create(e, code);
        }
    }

}
